package cn.hls.web.controller.dict;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hls.entity.Area;
import cn.hls.entity.Org;
import cn.hls.entity.vo.ExtTree;
import cn.hls.entity.vo.Msg;
import cn.hls.entity.vo.PageInfo;
import cn.hls.service.AreaService;
import cn.hls.web.controller.base.BaseController;

@Controller
@RequestMapping("/area")
public class AreaController extends BaseController<Area> {
	@Resource(name = "areaService")
	private AreaService areaService;
	@RequestMapping("/add")
	@ResponseBody
	public Msg add(Area entity) throws Exception {
		Area area = areaService.findArea(entity);
		if (area != null) {// 对象存在
			msg.setStatus(201);
			msg.setInfo("区域名称或代码已经存在");
		} else {
			if(entity.getParent().getId()==0){
				entity.setParent(null);
			}
			boolean flag = areaService.add(entity);
			if (!flag) {
				msg.setStatus(202);
				msg.setInfo("操作失败");
			}else{
				msg.setInfo("操作成功");
				msg.setStatus(200);
				msg.setSuccess(true);
			}
		}
		return msg;
	} 
	
	@RequestMapping("/update")
	@ResponseBody
	public Msg update(Area entity) throws Exception {
		if(entity.getParent().getId()==0){
			entity.setParent(null);
		}
		boolean flag = areaService.update(entity);
		if (!flag) {
			msg.setStatus(201);
			msg.setInfo("操作失败");
		}else{
			msg.setInfo("操作成功");
			msg.setStatus(200);
			msg.setSuccess(true);
		}
		return msg;
	}

	@ResponseBody
	@RequestMapping("/del")
	public Msg del(Long id) throws Exception {
		String result = areaService.delete(id);
		if (!result.equalsIgnoreCase("ok")) {
			msg.setStatus(201);
			msg.setInfo(result);
		}else{
			msg.setInfo("操作成功");
			msg.setStatus(200);
			msg.setSuccess(true);
		}
		return msg;
	}

	// 排序
	@ResponseBody
	@RequestMapping("/sort")
	public Msg sort(String ids) throws Exception {
		try {
			areaService.updateSort(ids);
			msg.setStatus(200);
			msg.setInfo("操作成功");
			return msg;
		} catch (Exception e) {
			msg.setInfo("操作失败");
			msg.setStatus(201);
			throw e;
		}
	}

	@RequestMapping("/view")
	public String view() {
		return "dict/area";
	}

	@RequestMapping("/list")
	@ResponseBody
	public PageInfo<Area> list( PageInfo<Area> page,Area entity) throws Exception {
		return areaService.loadAreaInfo(page, entity);
	}
	@RequestMapping("/areaList")
	@ResponseBody
	public List<Area> areaList(Long fatherId)throws Exception{
		Area entity=new Area();
		entity.setId(fatherId);
		return areaService.loadAreaList(entity);
	}
	
	@ResponseBody
	@RequestMapping("/tree")
	public List<ExtTree> tree(Area entity, Long nodeId) throws Exception {
		return areaService.loadChildAreaInfo(entity, nodeId == null	|| nodeId == 0 ? null : nodeId);
			
	}

	 
}
